package com.yu.mall.filter;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

public class ParamHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 微信openId
     */
    private final static String OPEN_ID = "openid";

    public ParamHttpServletRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Set<String> names = new LinkedHashSet();
        names.addAll(Collections.list(super.getParameterNames()));
        String openId = super.getHeader(OPEN_ID);
        if(!StringUtils.isEmpty(openId)){
            names.add(OPEN_ID);
        }
        return Collections.enumeration(names);
    }
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if(OPEN_ID.equalsIgnoreCase(parameter)){
            String openId = super.getHeader(OPEN_ID);
            return new String[]{openId};
        }
        if (values == null) {
            return new String[0];
        }

        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = values[i].trim();
            if(StringUtils.isEmpty(values[i])){
                encodedValues[i] = null;
            }
        }
        return encodedValues;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = new HashMap<String, String[]>();
        parameterMap.putAll(super.getParameterMap());
        String openId = super.getHeader(OPEN_ID);
        if(!StringUtils.isEmpty(openId)){
            String[] value = new String[]{openId};
            parameterMap.put(OPEN_ID,value);
        }
        return parameterMap;
    }

    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return value.trim();
    }
}